package com.hnichr.crm.biz.customer.service.impl;

import cn.hutool.core.date.DateUtil;
import com.hnichr.crm.common.customer.entity.CrmCustomer;
import com.hnichr.crm.common.customer.service.ICrmCustomerService;
import com.hnichr.crm.common.product.entity.CrmProduct;
import com.hnichr.crm.common.report.vo.CrmAnalysis;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.initiator.JpaUtilAble;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.security.entity.Dept;
import com.mxpioframework.security.entity.UserDept;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户管理Service业务层处理
 *
 * @author Cheng
 * @date 2022-11-22
 */
@Service
public class CrmCustomerServiceImpl implements ICrmCustomerService, JpaUtilAble {
    @Override
    public void afterPropertiesSet(ApplicationContext applicationContext) {

    }

    @Override
    @Transactional(readOnly = true)
    public Page<CrmCustomer> page(Criteria criteria, Pageable pageable) {
        return JpaUtil.linq(CrmCustomer.class).where(criteria).paging(pageable);
    }

    @Override
    @Transactional(readOnly = true)
    public CrmCustomer getById(String id) {
        return JpaUtil.linq(CrmCustomer.class).idEqual(id).findOne();
    }

    @Override
    @Transactional(readOnly = false)
    public String save(CrmCustomer crmCustomer) {
        Criteria criteria = Criteria.create();
        criteria = criteria.or().addCriterion("customerName", Operator.EQ,crmCustomer.getCustomerName());
        if(StringUtils.isNotBlank(crmCustomer.getTaxId())){
            criteria = criteria.addCriterion("taxId", Operator.EQ,crmCustomer.getTaxId());
        }
        criteria = criteria.end();
        List<CrmCustomer> existsList = JpaUtil.linq(CrmCustomer.class).where(criteria).list();
        if(CollectionUtils.isEmpty(existsList)){
            JpaUtil.save(crmCustomer);
            return "";
        }
        CrmCustomer existsCustomer = existsList.get(0);
        if(StringUtils.isNotBlank(crmCustomer.getTaxId())&&StringUtils.equals(crmCustomer.getTaxId(),existsCustomer.getTaxId())){
            return "纳税人识别号为["+crmCustomer.getTaxId()+"]的客户已存在！";
        }
        else{
            return "客户名称为["+crmCustomer.getCustomerName()+"]的客户已存在！";
        }
    }

    @Override
    @Transactional(readOnly = false)
    public String update(CrmCustomer crmCustomer) {
        Criteria criteria = Criteria.create();
        criteria = criteria.or().addCriterion("customerName", Operator.EQ,crmCustomer.getCustomerName());
        if(StringUtils.isNotBlank(crmCustomer.getTaxId())){
            criteria = criteria.addCriterion("taxId", Operator.EQ,crmCustomer.getTaxId());
        }
        criteria = criteria.end().and().addCriterion("id",Operator.NE,crmCustomer.getId()).end();
        List<CrmCustomer> existsList = JpaUtil.linq(CrmCustomer.class).where(criteria).list();
        if(CollectionUtils.isEmpty(existsList)){
            JpaUtil.update(crmCustomer);
            return "";
        }
        CrmCustomer existsCustomer = existsList.get(0);
        if(StringUtils.isNotBlank(crmCustomer.getTaxId())&&StringUtils.equals(crmCustomer.getTaxId(),existsCustomer.getTaxId())){
            return "纳税人识别号为["+crmCustomer.getTaxId()+"]的客户已存在！";
        }
        else{
            return "客户名称为["+crmCustomer.getCustomerName()+"]的客户已存在！";
        }

    }

    @Override
    @Transactional(readOnly = false)
    public int delete(String id) {
        return JpaUtil.lind(CrmCustomer.class).equal("id", id).delete();
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> getDeptCodes() {
        String loginUsername = SecurityUtils.getLoginUsername();
        List<UserDept> list = JpaUtil.linq(UserDept.class)
                .equal("userId",loginUsername)
                .list();
        List<String> deptIds = list.stream().map(item -> item.getDeptId()).collect(Collectors.toList());
        List<Dept> deptList = JpaUtil.linq(Dept.class)
                .in("id",deptIds)
                .list();
        List<String> deptCodes = deptList.stream().map(item -> item.getDeptCode()).collect(Collectors.toList());
        return deptCodes;
    }

    @Override
    @Transactional(readOnly = true)
    public CrmAnalysis getAnalysis() {
        CrmAnalysis crmAnalysis = new CrmAnalysis();
        Date now = new Date();
        //客户
        Long customerTotal = JpaUtil.linq(CrmCustomer.class).count();
        Long customerAdd = JpaUtil.linq(CrmCustomer.class).between("createTime", DateUtil.beginOfDay(now), DateUtil.endOfDay(now)).count();
        crmAnalysis.setCustomerTotal(customerTotal);
        crmAnalysis.setCustomerAdd(customerAdd);

        //项目
        Long projectTotal = JpaUtil.linq(CrmProduct.class).count();
        Long projectAdd = JpaUtil.linq(CrmProduct.class).between("createTime", DateUtil.beginOfDay(now), DateUtil.endOfDay(now)).count();
        crmAnalysis.setProjectTotal(projectTotal);
        crmAnalysis.setProjectAdd(projectAdd);


        return crmAnalysis;
    }
}
